//
//  SettingPayPasswordViewController.swift
//  Exchange
//
//  Created by rui on 2018/6/7.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class SettingPayPasswordViewController: AccountBaseViewController {
    @IBOutlet weak var tibLable: UILabel!
    @IBOutlet weak var passButton: UIButton!
    @IBOutlet weak var passwordInputView: VerifyCodeInputView!
    var fisrtPayPwd: String = ""
    var lastPayPwd: String = ""
    lazy var viewModel: SettingPayPasswordViewModel = {
        let vm = SettingPayPasswordViewModel()
       vm.response = {[weak self](state,isSuccess,errorMsg)in
            if state == ResponseState.mine_payPwd  {
                if isSuccess {
                    CYMBShow.showMessage(kText("设置支付密码成功"))
                }else {
                    if let msg = errorMsg, let weakSelf = self {
                       CYMBShow.showMessage(msg)
                    }else {
                         CYMBShow.showMessage(kText("设置支付密码失败"))
                    }
                }
                self?.navigationController?.popToRootViewController(animated: true)
            }
        }
        return vm
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
    }
    
    func initUI() {
        self.passButton.setTitle(kText("暂不设置"), for: UIControlState.normal);
        self.title = kText("设置支付密码")
        tibLable.text = nil
    
        passButton.themeSetTitleColor(ThemeManager.ThemeColorKeys.text1, for: .normal)
        passwordInputView.beginEdit()
        passwordInputView.isSecurity = true
        
        passwordInputView.verifyCodeChange = {[weak self] (text) in
          self?.verifyCodeChange(text: text)
        }
    }
    
    func verifyCodeChange(text: String) {
        if text.count == 6 {
            if self.fisrtPayPwd.count > 0 {
                self.lastPayPwd = text
                //完成输入
                if self.fisrtPayPwd == self.lastPayPwd  {
                    self.viewModel.settingPayPwd(payPassword: self.lastPayPwd)
                }else {
                    CYMBShow.showMessage(kText("两次密码设置不一致,请重新输入"))
                    self.passwordInputView.text = nil
                    self.tibLable.text = nil
                }
            }else {
                self.passwordInputView.text = nil
                self.passwordInputView.beginEdit()
                self.fisrtPayPwd = text
                self.tibLable.text = kText("请再次输入")
            }
        }
    }
    
    @objc func back() {
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    override func customBackItem() -> UIBarButtonItem? {
        let item = UIBarButtonItem(image: #imageLiteral(resourceName: "nav_icon_back"), style: .plain, target: self, action: #selector(back))
        return item
    }
    
    @IBAction func passBtnCilck(_ sender: UIButton) {
        self.navigationController?.popToRootViewController(animated: true)
    }
}
